package com.kedacom.freedomLabel;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;

import com.kedacom.freedomLabel.model.db.AppDatabase;
import com.kedacom.freedomLabel.utils.FileIOUtils;
import com.kedacom.freedomLabel.utils.log.LLog;
import com.kedacom.lego.annotation.LogOff;
import com.kedacom.lego.fast.LegoFastApplication;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;


@LogOff
public class MainApplication extends LegoFastApplication {

    private static final int MIN_DELAY_TIME = 1000;
    private static long lastClickTime;

    public static boolean isFastClick() {
        long currentClickTime = System.currentTimeMillis();
        if ((currentClickTime - lastClickTime) >= MIN_DELAY_TIME) {
            return false;
        }
        lastClickTime = currentClickTime;
        return true;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        registerActivityLifecycleCallbacks();
        AppDatabase.getInstance();
        FileIOUtils.init(this);
//        Bugly.init(getApplicationContext(), "6264889eea", false);
        LLog.init(BuildConfig.DEBUG, false, 30);
    }

    @Override
    protected void setLegoCrashHandler() {
//        LegoCrashHandler handler = LegoCrashHandler.getInstance().init(this);
//        // 错误或异常 callback 处理告警消息业务
//        handler.addCrashCallback((thread, ex) -> {
//            LegoActivityManager.clear();
//            android.os.Process.killProcess(android.os.Process.myPid());
//        });
    }

    private void registerActivityLifecycleCallbacks() {
        registerActivityLifecycleCallbacks(new ActivityLifecycleCallbacks() {

            @Override
            public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
                LLog.debug("创建视图窗口-" + activity.getClass().getSimpleName());
            }

            @Override
            public void onActivityStarted(Activity activity) {
//                String title = activity.getTitle().toString();
//                K5Logger.activityLog("打开-" + title);
            }

            @Override
            public void onActivityResumed(Activity activity) {

            }

            @Override
            public void onActivityPaused(Activity activity) {
            }

            @Override
            public void onActivityStopped(Activity activity) {
            }

            @Override
            public void onActivitySaveInstanceState(Activity activity, Bundle outState) {

            }

            @Override
            public void onActivityDestroyed(Activity activity) {
                LLog.debug("销毁视图窗口-" + activity.getClass().getSimpleName());
//                String title = activity.getTitle().toString();
//                if (!title.equals(getString(R.string.app_name))) {
//                    K5Logger.activityLog("关闭-" + title);
//                }
            }
        });
    }

    @Override
    protected void attachBaseContext(android.content.Context base) {
        super.attachBaseContext(base);
        android.support.multidex.MultiDex.install(this);
    }

    public void addClickProxy(View view) {
        if (view instanceof ViewGroup) {
            try {
                setViewProxy((ViewGroup) view);
            } catch (IllegalAccessException | InvocationTargetException e) {
                e.printStackTrace();
            }
        } else {
            try {
                hook(view);
            } catch (IllegalAccessException | InvocationTargetException e) {
                e.printStackTrace();
            }
        }
    }

    private void setViewProxy(ViewGroup viewGroup) throws IllegalAccessException, InvocationTargetException {
        hook(viewGroup);
        int count = viewGroup.getChildCount();
        for (int i = 0; i < count; i++) {
            if (viewGroup.getChildAt(i) instanceof ViewGroup) {
                setViewProxy((ViewGroup) viewGroup.getChildAt(i));
            } else {
                hook(viewGroup.getChildAt(i));
            }
        }
    }

    private void hook(View view) throws IllegalAccessException, InvocationTargetException {
        if (!view.hasOnClickListeners()) return;
        try {
            Method getListenerInfo = View.class.getDeclaredMethod("getListenerInfo");
            getListenerInfo.setAccessible(true);
            Object listenereInfo = getListenerInfo.invoke(view);
            try {
                Class<?> listenerInfoClazz = Class.forName("android.view.View$ListenerInfo");
                try {
                    Field mOnClickListener = listenerInfoClazz.getDeclaredField("mOnClickListener");
                    mOnClickListener.setAccessible(true);
                    View.OnClickListener originOnClickListener = (View.OnClickListener) mOnClickListener.get(listenereInfo);
                    if (originOnClickListener == null || originOnClickListener instanceof MyWrapperOnClickListener) {
                        return;
                    }
                    MyWrapperOnClickListener proxyOnClick = new MyWrapperOnClickListener(originOnClickListener);
                    view.setOnClickListener(proxyOnClick);
                } catch (NoSuchFieldException e) {
                    e.printStackTrace();
                }
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        }
    }

    private class MyWrapperOnClickListener implements View.OnClickListener {

        private View.OnClickListener onClickListener;

        MyWrapperOnClickListener(View.OnClickListener onClickListener) {
            this.onClickListener = onClickListener;
        }

        @Override
        public void onClick(View v) {
            if (isFastClick()) {
                return;
            }
            preClick();
            onClickListener.onClick(v);
            afterClick(v);
        }

        private void preClick() {
        }

        private void afterClick(View view) {
        }
    }
}